<script setup>
import postHouseApi from '../api/PostHouse_api.js'
import classificationApi from '../api/Classification_api.js'
import commentApi from '../api/CommentApi.js'
import giveApi from '../api/Give_api.js'
import loginApi from '../api/Login_api.js' // 新增：导入登录API
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import post_api from "@/api/Post_api.js";

const tableData = ref([]);
const total = ref(0);
const loading = ref(true);
const search = ref('');
const comments = ref([]);
const loadingComments = ref(false);
const currentPost = ref({});

// 点赞相关状态
const likeStatus = ref({});
const likeCounts = ref({});
const likeLoading = ref({});

// 查询参数
const searchObj = ref({
  current: 1,
  limit: 10,
  keyword: '',
});

const typename = ref([])
const post = ref({
  id: '',
  userId: '',
  typeId: '',
  postTitle: '',
  postContent: '',
  postSummary: '',
  giveCount: '',
  commentCount: '',
  status: '',
  isVisible: 0,
})

// 评论相关状态
const newComment = ref('');
const replyComment = ref(null);
const replyContent = ref('');
const replyToComment = ref(null);

// 修改：从登录信息获取当前用户ID
const currentUserId = ref(null);
const currentUserInfo = ref(null);

const drawerVisible = ref([]);
const innerDrawer = ref(false)

// ========== 新增：获取当前登录用户信息 ==========
/**
 * 获取当前登录用户信息
 */
const getCurrentUserInfo = async () => {
  try {
    const userInfo = await loginApi.loginInfo();
    currentUserInfo.value = userInfo;
    currentUserId.value = userInfo.id; // 假设用户信息中有id字段
    console.log('当前用户信息:', userInfo);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
    // 可以设置一个默认用户ID或跳转到登录页面
    currentUserId.value = 1; // 临时默认值
  }
};

// ========== 新增：构建评论树函数 ==========
/**
 * 将扁平评论列表转换为树形结构
 */
const buildCommentTree = (flatComments) => {
  if (!flatComments || !flatComments.length) return [];

  // 创建评论映射表
  const commentMap = {};
  flatComments.forEach(comment => {
    commentMap[comment.id] = { ...comment, replies: [] };
  });

  // 构建树形结构
  const tree = [];
  flatComments.forEach(comment => {
    if (comment.parentId) {
      // 如果存在父评论，添加到父评论的replies中
      if (commentMap[comment.parentId]) {
        commentMap[comment.parentId].replies.push(commentMap[comment.id]);
      }
    } else {
      // 如果没有父评论，则是顶级评论
      tree.push(commentMap[comment.id]);
    }
  });

  return tree;
};

// ========== 修改位置：修复初始化点赞状态函数 ==========
/**
 * 初始化点赞状态
 */
const initLikeStatus = async () => {
  for (const item of tableData.value) {
    const postId = item.id;
    if (postId && currentUserId.value) {
      try {
        // 检查点赞状态
        const statusRes = await giveApi.checkLikeStatus(currentUserId.value, postId);
        likeStatus.value[postId] = statusRes;

        // 获取点赞数量
        const countRes = await giveApi.getLikeCount(postId);
        likeCounts.value[postId] = countRes;

        // 更新帖子显示的点赞数
        item.giveCount = countRes;
      } catch (error) {
        console.error('初始化点赞状态失败:', error);
        likeStatus.value[postId] = false;
        likeCounts.value[postId] = item.giveCount || 0;
      }
    }
  }
};

// ========== 修改位置：修复点赞处理函数 ==========
/**
 * 处理点赞/取消点赞
 */
const handleLike = async (postId, index) => {
  if (likeLoading.value[postId] || !currentUserId.value) return;

  likeLoading.value[postId] = true;
  try {
    const giveData = {
      userId: currentUserId.value,
      postId: postId,
      comId: null
    };

    const res = await giveApi.toggleGive(giveData);
    likeStatus.value[postId] = res;

    // 更新点赞数量
    const countRes = await giveApi.getLikeCount(postId);
    likeCounts.value[postId] = countRes;

    // 更新界面显示的点赞数
    tableData.value[index].giveCount = countRes;
    // ElMessage.success(res ? '点赞成功' : '取消点赞成功');
  } catch (error) {
    console.error('点赞操作失败:', error);
    ElMessage.error('操作失败');
  } finally {
    likeLoading.value[postId] = false;
  }
};

/**
 * 提交评论
 */
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('评论内容不能为空');
    return;
  }

  if (!currentUserId.value) {
    ElMessage.warning('请先登录');
    return;
  }

  try {
    const commentData = {
      postId: currentPost.value.id,
      userId: currentUserId.value, // 使用当前登录用户的ID
      commentContent: newComment.value.trim(),
      parentId: null
    };

    await commentApi.addComment(commentData);
    ElMessage.success('评论发表成功');
    newComment.value = '';
    await loadComments(currentPost.value.id);
  } catch (error) {
    console.error('发表评论失败:', error);
    ElMessage.error('评论发表失败: ' + (error.response?.data?.msg || error.message));
  }
};

/**
 * 提交回复
 */
const submitReply = async (parentComment) => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空');
    return;
  }

  if (!currentUserId.value) {
    ElMessage.warning('请先登录');
    return;
  }

  try {
    const replyData = {
      postId: currentPost.value.id,
      userId: currentUserId.value, // 使用当前登录用户的ID
      commentContent: replyContent.value.trim(),
      parentId: parentComment.id,
      replycomId: parentComment.userId
    };

    await commentApi.addComment(replyData);
    ElMessage.success('回复成功');
    replyContent.value = '';
    replyComment.value = null;
    replyToComment.value = null;
    await loadComments(currentPost.value.id);
  } catch (error) {
    console.error('回复失败:', error);
    ElMessage.error('回复失败');
  }
};

/**
 * 开始回复
 */
const startReply = (comment) => {
  if (!currentUserId.value) {
    ElMessage.warning('请先登录');
    return;
  }

  replyComment.value = comment;
  replyToComment.value = comment;
  replyContent.value = '';
};

/**
 * 取消回复
 */
const cancelReply = () => {
  replyComment.value = null;
  replyToComment.value = null;
  replyContent.value = '';
};

/**
 * 打开抽屉显示帖子详情
 */
const openDrawer = (index) => {
  currentPost.value = tableData.value[index];
  drawerVisible.value[index] = true;
};

/**
 * 打开内部抽屉显示评论
 */
const openInnerDrawer = async () => {
  innerDrawer.value = true;
  await loadComments(currentPost.value.id);
};

// ========== 修改位置：修复加载评论函数 ==========
/**
 * 加载评论数据
 */
const loadComments = async (postId) => {
  loadingComments.value = true;
  try {
    console.log(postId);
    const response = await commentApi.getCommentsByPost(postId);
    console.log(response);
    // 构建评论树形结构
    let commentTree;
    if (response && response.length > 0) {
      // 检查第一个评论是否已经有replies属性（已经是树形结构）
      if (response[0].replies) {
        commentTree = response;
      } else {
        // 如果是扁平结构，转换为树形结构
        commentTree = buildCommentTree(response);
      }
    } else {
      commentTree = [];
    }
    comments.value = commentTree;
    console.log('加载的评论数据:', comments.value);
  } catch (error) {
    console.error('加载评论失败:', error);
    ElMessage.error('评论加载失败');
    comments.value = [];
  } finally {
    loadingComments.value = false;
  }
};

// ========== 修改位置：修复数据获取函数 ==========
/**
 * 获取帖子列表数据
 */
const fetchData = async () => {
  loading.value = true;
  try {
    let res;
    if (searchObj.value.keyword) {
      res = await postHouseApi.search({keyword: searchObj.value.keyword});
      tableData.value = res.data || [];
      total.value = res.data?.length || 0;
    } else {
      res = await postHouseApi.page(searchObj.value);
      if (Array.isArray(res.data)) {
        tableData.value = res.data;
        total.value = res.data.length;
      } else if (res.data && Array.isArray(res.data.records)) {
        tableData.value = res.data.records;
        total.value = res.data.total || 0;
      } else {
        tableData.value = [];
        total.value = 0;
      }
    }

    // 初始化点赞状态
    await initLikeStatus();

  } catch (error) {
    console.error('API请求错误:', error);
    ElMessage.error(`数据加载失败: ${error.message || '网络错误'}`);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/**
 * 处理搜索
 */
const handleSearch = () => {
  searchObj.value.keyword = search.value.trim();
  searchObj.value.current = 1;
  fetchData();
};

/**
 * 按类型筛选
 */
const handleType = async () => {
  if (post.value.typeId) {
    const res = await post_api.listBytype(post.value.typeId);
    tableData.value = Array.isArray(res) ? res : (res.data || []);
    // 重新初始化点赞状态
    await initLikeStatus();
  } else {
    post.value.typeId = '';
    await fetchData();
  }
};

/**
 * 处理分页变化
 */
const handlePageChange = (newPage) => {
  searchObj.value.current = newPage;
  fetchData();
};

/**
 * 获取当前类型
 * @returns {Promise<void>}
 */
const classification = async ()=>{
  const typeRes = await classificationApi.list();
  console.log(typeRes);
  typename.value = typeRes;
  console.log(typename);
}

// 组件挂载时初始化数据
onMounted(async () => {
  // 先获取用户信息
  await getCurrentUserInfo();
  // 然后获取其他数据
  await fetchData();
  await classification();
});
</script>

<template>
  <div style="display: flex; justify-content: center; margin-bottom: 20px; gap: 20px; align-items: center;">
    <el-input
        v-model="search"
        placeholder="输入关键词搜索帖子..."
        style="width: 300px;"
        clearable
        @keyup.enter="handleSearch"
    >
    </el-input>

    <el-form :inline="true" style="margin: 0;">
      <el-form-item style="margin: 0;" v-model="typename">
        <el-select
            v-model="post.typeId"
            placeholder="请选择类型"
            style="width: 240px"
        >
          <el-option
              v-for="item in typename"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
          >
          </el-option>
          <el-option label="全部" :value="''"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin: 0 0 0 10px;">
        <el-button type="primary" @click="handleType">查询</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 帖子列表区域 -->
  <div style="display: flex; justify-content: center;">
    <div style="width: 100%; max-width: 1200px;">
      <div style="display: flex; flex-wrap: wrap; gap: 20px; justify-content: flex-start;">
        <div
            v-for="(item, index) in tableData"
            :key="item.id || index"
            style="width: calc(25% - 15px); min-width: 280px;"
        >
          <el-card
              shadow="hover"
              :body-style="{ padding: '15px' }"
              style="height: 220px; display: flex; flex-direction: column;"
          >
            <!-- 卡片头部 - 用户信息 -->
            <div style="margin-bottom: 12px;">
              <div style="display: flex; align-items: center; margin-bottom: 8px;">
                <span style="font-size: 14px; color: #666; font-weight: 500;">
                  {{ item.userNickname || '匿名用户' }}
                </span>
              </div>

              <!-- 帖子标题 -->
              <h3 style="margin: 0 0 10px 0; font-size: 16px; font-weight: 600; color: #333; line-height: 1.4;
                         display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;">
                {{ item.postTitle || '无标题帖子' }}
              </h3>
            </div>

            <!-- 帖子摘要 -->
            <div style="flex: 1; margin-bottom: 15px;">
              <el-button text @click="openDrawer(index)">
                <p style="margin: 0; font-size: 14px; color: #666; line-height: 1.5;
                       display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;">
                  {{ item.postSummary || '暂无摘要' }}
                </p>
              </el-button>
              <el-drawer v-model="drawerVisible[index]"
                         title="帖子内容"
                         direction="rtl"
                         size="50%">
                <div class="drawer-content">
                  <h3 class="drawer-title">{{ item.postTitle || '无标题帖子' }}</h3>
                  <p style="white-space: pre-wrap;">{{ item.postContent || '暂无内容' }}</p>

                  <div style="margin-top: 30px; text-align: center;">
                    <el-button type="primary" @click="drawerVisible[index] = false">关闭</el-button>
                    <el-button @click="openInnerDrawer">查看评论 ({{ item.commentCount || 0 }})</el-button>
                    <el-drawer
                        v-model="innerDrawer"
                        title="评论区"
                        :append-to-body="true"
                        direction="rtl"
                        size="40%">
                      <div v-if="currentPost" class="comments-container">
                        <!-- 显示当前用户信息 -->
                        <div v-if="currentUserInfo" class="current-user-info" style="margin-bottom: 15px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
                          当前用户: {{ currentUserInfo.userNickname || currentUserInfo.username }}
                        </div>

                        <!-- 发表评论区域 -->
                        <div class="comment-input-area">
                          <el-input
                              v-model="newComment"
                              type="textarea"
                              :rows="3"
                              placeholder="请输入评论内容"
                              resize="none"
                              maxlength="500"
                              show-word-limit
                          ></el-input>
                          <div style="text-align: right; margin-top: 10px;">
                            <el-button type="primary" @click="submitComment">发表评论</el-button>
                          </div>
                        </div>

                        <!-- 评论列表 -->
                        <div class="comments-list">
                          <div v-if="comments.length > 0">
                            <!-- 一级评论 -->
                            <div v-for="(comment, commentIndex) in comments" :key="commentIndex" class="comment-item">
                              <div class="comment-header">
                                <span class="comment-author">{{ comment.userNickname || '匿名用户' }}</span>
                                <span v-if="comment.replyUserNickname" class="reply-to-info">
                                  回复 @{{ comment.replyUserNickname }}
                                </span>
                              </div>
                              <div class="comment-content">{{ comment.commentContent }}</div>

                              <div class="comment-actions">
                                <el-button link type="primary" @click="startReply(comment)">回复</el-button>
                              </div>

                              <!-- 回复输入框 -->
                              <div v-if="replyToComment && replyToComment.id === comment.id" class="reply-input-area">
                                <el-input
                                    v-model="replyContent"
                                    type="textarea"
                                    :rows="2"
                                    placeholder="请输入回复内容"
                                    resize="none"
                                    maxlength="300"
                                    show-word-limit
                                ></el-input>
                                <div style="text-align: right; margin-top: 10px;">
                                  <el-button size="small" @click="cancelReply">取消</el-button>
                                  <el-button size="small" type="primary" @click="submitReply(comment)">发表回复</el-button>
                                </div>
                              </div>

                              <!-- 二级评论 -->
                              <div v-if="comment.replies && comment.replies.length" class="replies-container">
                                <div v-for="(reply, replyIndex) in comment.replies" :key="replyIndex" class="comment-item reply-item">
                                  <div class="comment-header">
                                    <span class="comment-author">{{ reply.userNickname || '匿名用户' }}</span>
                                    <span v-if="reply.replyUserNickname" class="reply-to-info">
                                      回复 @{{ reply.replyUserNickname }}
                                    </span>
                                  </div>
                                  <div class="comment-content">{{ reply.commentContent }}</div>

                                  <div class="comment-actions">
                                    <el-button link type="primary" @click="startReply(reply)">回复</el-button>
                                  </div>

                                  <!-- 回复输入框 -->
                                  <div v-if="replyToComment && replyToComment.id === reply.id" class="reply-input-area">
                                    <el-input
                                        v-model="replyContent"
                                        type="textarea"
                                        :rows="2"
                                        placeholder="请输入回复内容"
                                        resize="none"
                                        maxlength="300"
                                        show-word-limit
                                    ></el-input>
                                    <div style="text-align: right; margin-top: 10px;">
                                      <el-button size="small" @click="cancelReply">取消</el-button>
                                      <el-button size="small" type="primary" @click="submitReply(reply)">发表回复</el-button>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                          <div v-else class="empty-comments">
                            <el-empty description="暂无评论" :image-size="100"></el-empty>
                          </div>
                        </div>
                      </div>
                      <template #footer>
                        <el-button @click="innerDrawer = false">关闭</el-button>
                      </template>
                    </el-drawer>
                  </div>
                </div>
              </el-drawer>
            </div>

            <!-- 卡片底部 - 统计信息 -->
            <template #footer>
              <div
                  style="display: flex; align-items: center; justify-content: space-around; padding-top: 10px; border-top: 1px solid #f0f0f0;">
                <!-- 点赞按钮 -->
                <el-button
                    :loading="likeLoading[item.id]"
                    :type="likeStatus[item.id] ? 'primary' : 'default'"
                    text
                    @click="handleLike(item.id, index)"
                    style="display: flex; align-items: center; color: #999; font-size: 13px;"
                >
                  <el-icon>
                    <Star/>
                  </el-icon>
                  <span style="font-weight: 500; margin-left: 4px;">{{ item.giveCount || 0 }}</span>
                </el-button>

                <!-- 评论数量 -->
                <span style="display: flex; align-items: center; color: #999; font-size: 13px;">
                  <el-icon><ChatDotRound/></el-icon>
                  <span style="font-weight: 500; margin-left: 4px;">{{ item.commentCount || 0 }}</span>
                </span>
              </div>
            </template>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.comments-container {
  padding: 20px;
}

.comment-input-area {
  margin-bottom: 20px;
}

.comment-item {
  padding: 15px;
  margin-bottom: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #fafafa;
}

.reply-item {
  background-color: #f5f7fa;
  margin-left: 20px;
  margin-top: 10px;
}

.replies-container {
  margin-top: 10px;
  border-left: 2px solid #e0e0e0;
  padding-left: 10px;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.comment-author {
  font-weight: 600;
  color: #409EFF;
}

.reply-to-info {
  color: #67C23A;
  margin-left: 8px;
  font-size: 13px;
}

.comment-content {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 10px;
}

.comment-actions {
  margin-top: 10px;
}

.reply-input-area {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.empty-comments {
  text-align: center;
  padding: 40px 0;
}

.drawer-content {
  padding: 20px;
}

.drawer-title {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}
</style>